package com.litelimit.core.strategy.core;

import com.litelimit.core.limit.annotation.LiteLimit;
import com.litelimit.core.service.loader.LuaScriptLoader;
import com.litelimit.core.service.log.LiteLimitLog;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;

/**
 * 限流策略接口
 */
@RequiredArgsConstructor
public abstract class AbstractLimitStrategy implements LimitStrategy {

    protected final StringRedisTemplate stringRedisTemplate;
    protected final LuaScriptLoader luaScriptLoader;

    protected String keyPrefix = "lite:limit:";

    public boolean doLimit(LiteLimit limit, String key){
        long seconds = limit.unit().toSeconds(limit.period());
        long periodSe = seconds == 0 ? 1 : seconds;
        Boolean execute = stringRedisTemplate.execute(luaScriptLoader.getScript(),
                List.of(key), String.valueOf(limit.max()), String.valueOf(periodSe));
        if (execute) {
            return true;
        } else {
            LiteLimitLog.log.error(key + "被限流");
            return false;
        }
    }
}
